package common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionUtil {
    private static final Logger logger = LoggerFactory.getLogger(TransactionUtil.class);

    public static Object transactionInvoke(TransactionInvoke invoke, Connection conn) {
        try {
            conn.setAutoCommit(false);
            Object object = invoke.invoke(conn);
            conn.commit();
            return object;
        } catch (Exception e) {
            logger.error("保存失败!", e);
            try {
                conn.rollback();
            } catch (SQLException ex) {
                logger.error("事务回滚失败！", e);
            }
            throw new RuntimeException(e);
        }
    }


    public interface TransactionInvoke{
        Object invoke(Connection conn);
    }

}
